package com.coldworks.coldjoke.task;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.coldworks.base.BaseThread;
import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.base.util.BaseCONST;
import com.coldworks.coldjoke.manager.UserManager;
import com.coldworks.coldjoke.model.JokeModel;
import com.coldworks.coldjoke.util.NetworkUtil;
import com.coldworks.coldjoke.util.UrlUtil;

public class GetVotesTask extends BaseThread {

	private Handler handler;
	private Context context;
	private String jokeIds = "";
	private List<NameValuePair> params;

	// private List<JokeModel> jokeInfos;

	public GetVotesTask(Context context, Handler handler,
			List<JokeModel> jokeInfos) {
		this.context = context;
		this.handler = handler;
		// this.jokeInfos = jokeInfos;
		int i;
		for (i = 0; i < jokeInfos.size() - 1; i++) {
			jokeIds = jokeIds + jokeInfos.get(i).getJokeId() + "_";
		}
		jokeIds = jokeIds + jokeInfos.get(i).getJokeId();
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("action", "getJokeLikeStates"));
		params.add(new BasicNameValuePair("joke_ids", jokeIds));
	}

	@Override
	public void run() {
		HttpPost httpPost = new HttpPost(UrlUtil.getProfileUrl());
		Message message = null;
		try {
			String sessionId = UserManager.getInstance().getSessionId();
			httpPost.setHeader("COOKIE", "webpy_session_id=" + sessionId);
			httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			HttpResponse httpResponse = BaseNetworkManager.getInstance()
					.createHttpClient(context).execute(httpPost);
			if (isInterrupted()) {
				log.info("cancelled");
				if (handler == null) {
					return;
				}
				message = handler.obtainMessage(BaseCONST.OP.CANCEL);
				return;
			}
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				Header contentEncoding = httpResponse
						.getFirstHeader("Content-Encoding");
				JSONObject jsonObject = null;
				if (contentEncoding != null
						&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					jsonObject = NetworkUtil.getInstance().getJsonObjectByGzip(
							httpResponse.getEntity().getContent());
				} else {
					jsonObject = NetworkUtil.getInstance().getJSONObject(
							httpResponse.getEntity().getContent());
				}
				if (jsonObject == null) {
					log.info("error-->json=null");
					// for (int i = 0; i < jokeInfos.size(); i++) {
					// JokeModel jokeInfo = jokeInfos.get(i);
					// jokeInfo.setLikeState(JokeInfo.UNKNOWN);
					// }
					if (handler == null) {
						return;
					}
					message = handler.obtainMessage(BaseCONST.OP.ERR_NET);
					return;
				}
				// for (int i = 0; i < jokeInfos.size(); i++) {
				// JokeModel jokeInfo = jokeInfos.get(i);
				// jokeInfo.setLikeState(getJokeVote(jsonObject,
				// jokeInfo.getJokeId()));
				// }
				log.info("succ");
				if (handler == null) {
					return;
				}
				message = handler.obtainMessage(BaseCONST.OP.SUCC);
				return;
			} else {
				log.info("error net-->code:"
						+ httpResponse.getStatusLine().getStatusCode());
				// for (int i = 0; i < jokeInfos.size(); i++) {
				// JokeModel jokeInfo = jokeInfos.get(i);
				// jokeInfo.setLikeState(JokeInfo.UNKNOWN);
				// }
				if (handler == null) {
					return;
				}
				message = handler.obtainMessage(BaseCONST.OP.ERR_NET);
				return;
			}
		} catch (Exception e) {
			log.error("", e);
			// for (int i = 0; i < jokeInfos.size(); i++) {
			// JokeModel jokeInfo = jokeInfos.get(i);
			// jokeInfo.setLikeState(JokeInfo.UNKNOWN);
			// }
			if (handler == null) {
				return;
			}
			message = handler.obtainMessage(BaseCONST.OP.ERR_NET);
			return;
		} finally {
			if (handler != null) {
				handler.sendMessage(message);
			}

		}
	}

	public int getJokeVote(JSONObject jsonObject, String jokeId) {
		try {
			JSONObject json = jsonObject.getJSONObject(jokeId);
			if (!json.getBoolean("isLiked") && !json.getBoolean("isUnliked")) {
				return JokeModel.UNKNOWN;
			}

			if (json.getBoolean("isLiked") && !json.getBoolean("isUnliked")) {
				return JokeModel.LIKE;
			}

			if (!json.getBoolean("isLiked") && json.getBoolean("isUnliked")) {
				return JokeModel.DISLIKE;
			}

		} catch (JSONException e) {
			log.error("", e);
			return JokeModel.UNKNOWN;
		}
		return JokeModel.UNKNOWN;
	}
}
